package com.sctvcloud.dongqu.ui.fragment;

import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.util.Pair;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.canyinghao.canrefresh.CanRefreshLayout;
import com.example.sdk.statisticssdk.StatisticsMainInit;
import com.google.gson.Gson;
import com.gridsum.tracker.GridsumWebDissector;
import com.jiongbull.jlog.JLog;
import com.ruihang.generalibrary.ui.dialog.ShareFragment;
import com.ruihang.generalibrary.ui.util.OnItemInternalClick;
import com.ruihang.generalibrary.ui.widget.CustomFontTextView;
import com.ruihang.generalibrary.utils.ListUtils;
import com.ruihang.generalibrary.utils.UrlUtils;
import com.sctvcloud.dongqu.R;
import com.sctvcloud.dongqu.application.Constances;
import com.sctvcloud.dongqu.base.BaseActivity;
import com.sctvcloud.dongqu.beans.FRebellion;
import com.sctvcloud.dongqu.beans.FUsers;
import com.sctvcloud.dongqu.beans.NewsClickCountBean;
import com.sctvcloud.dongqu.beans.NewsIdBean;
import com.sctvcloud.dongqu.beans.NewsItem;
import com.sctvcloud.dongqu.beans.NewsListClickRequestBean;
import com.sctvcloud.dongqu.beans.NewsListClickVo;
import com.sctvcloud.dongqu.beans.SingleResult;
import com.sctvcloud.dongqu.beans.TopicContent;
import com.sctvcloud.dongqu.http.AbsListNetCallback;
import com.sctvcloud.dongqu.http.AbsNetCallBack;
import com.sctvcloud.dongqu.http.NetUtils;
import com.sctvcloud.dongqu.http.ParamsEditor;
import com.sctvcloud.dongqu.ui.activities.ApplyCommitActivity;
import com.sctvcloud.dongqu.ui.activities.CityStaHomepageActivity;
import com.sctvcloud.dongqu.ui.activities.HudongActivity;
import com.sctvcloud.dongqu.ui.activities.LiveOriginalActivity;
import com.sctvcloud.dongqu.ui.activities.LoginActivity;
import com.sctvcloud.dongqu.ui.activities.MingshengActivity;
import com.sctvcloud.dongqu.ui.activities.ShareCommitActivity;
import com.sctvcloud.dongqu.ui.activities.ShareDetailActivity;
import com.sctvcloud.dongqu.ui.adapter.GreatestAdapter;
import com.sctvcloud.dongqu.ui.adapter.MingshengFrgAdapter;
import com.sctvcloud.dongqu.ui.adapter.ShareAdapter;
import com.sctvcloud.dongqu.ui.adapter.holder.ShareHolder;
import com.sctvcloud.dongqu.ui.adapter.holder.TopicHolder;
import com.sctvcloud.dongqu.ui.util.IListShowData;
import com.sctvcloud.dongqu.ui.util.RBaseItemDecoration;
import com.sctvcloud.dongqu.ui.utils.SkipUtil;
import com.sctvcloud.dongqu.ui.widget.PullToRefreshView;
import com.sctvcloud.dongqu.utils.UserManager;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.MediaType;
import okhttp3.RequestBody;

import static com.sctvcloud.dongqu.base.BaseActivity.DO_UP_POS;

/**
 * Created by raoweiwei on 2017/8/3.
 * 首页通用的其他列表栏目
 */

public class ShareMingshengFragment extends ColumnBaseFragment implements
        PullToRefreshView.OnHeaderRefreshListener , PullToRefreshView.OnFooterRefreshListener, TopicHolder.OnTopicSelectListener {

    @BindView(R.id.main_pull_refresh_view)
    PullToRefreshView mPullToRefreshView;
    @BindView(R.id.can_content_view1)
    protected RecyclerView mRecyclerView1;
    @BindView(R.id.can_content_view2)
    protected RecyclerView rebllion_list;
    @BindView(R.id.item_only_title_title1)
    protected CustomFontTextView title1;
    @BindView(R.id.tv_more1)
    protected TextView tv_more1;
    @BindView(R.id.tv_more2)
    protected TextView tv_more2;

    @BindView(R.id.title_top_edit_topic)
    protected CustomFontTextView publish;



    private MingshengFrgAdapter mAdapter;
    private boolean mIsLoading = false;
    private List<IListShowData> dataList = new ArrayList<>();

    private List<IListShowData> commonList = new ArrayList<>();
    protected static final int CODE_REQUEST_LOGIN = 303;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.item_mingsheng, container, false);
        ButterKnife.bind(this, view);
        return view;
    }

    @Override
    protected void initViews(View v, @Nullable Bundle savedInstanceState) {
        mPullToRefreshView.setOnHeaderRefreshListener(this);
        mPullToRefreshView.setOnFooterRefreshListener(this);


        mRecyclerView1.setItemAnimator(new DefaultItemAnimator());
        mRecyclerView1.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false));
        mRecyclerView1.addItemDecoration(new RBaseItemDecoration(1));


        rebllion_list.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false));
        rebllion_list.setItemAnimator(new DefaultItemAnimator());


        title1.setText(HomeFragment.getMingsheng_name());
        tv_more1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(getActivity(), MingshengActivity.class);
                intent.putExtra(BaseActivity.EX_TITLE,HomeFragment.getMingsheng_name());
                intent.putExtra(BaseActivity.EX_URL,HomeFragment.getMingsheng_url());
                startActivity(intent);
            }
        });
        tv_more2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(getActivity(), HudongActivity.class);
                startActivity(intent);
            }
        });

        publish.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!UserManager.isLoginS()) {
                    toLogin();
                    return;
                }
                Intent intent = new Intent(getContext(), ShareCommitActivity.class);
                startActivity(intent);
            }
        });
    }

    @Override
    protected boolean onFragmentShow(boolean isFirst, boolean isCallFromResume) {
        return super.onFragmentShow(isFirst, isCallFromResume);
    }

    @Override
    public void onResume() {
        getData();
        super.onResume();
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        if(!hidden){
            getData();
        }
        super.onHiddenChanged(hidden);
    }

    private void getData() {
        NetUtils.getNetAdapter().getNewsPage(getOwnerName(), HomeFragment.getMingsheng_url(), 0, new AbsListNetCallback<NewsItem>(null) {
            @Override
            public void onSuc(List<NewsItem> newsItems) {
                if (!ListUtils.isListValued(newsItems)) {
                    onError(null, null);
                    return;
                }


                if(newsItems.size()>=3){
                    newsItems = newsItems.subList(0,3);
                }


                requestNewsClickCount(newsItems, getPageResponse().getData().getTemplate());

            }

            @Override
            public void onError(Throwable ex, String errorMsg) {

            }

            @Override
            public void onEnd() {
                getDataHudong();
            }
        });
    }



    private void getDataHudong() {
        HashMap<String, Object> param = new HashMap<>();
        param.put("page", 0);
        param.put("size", 10);
        FUsers user = UserManager.getInstance().getUser();
        if (user != null && !TextUtils.isEmpty(user.getUserId())) {
            param.put("userId", user.getUserId());
        } else {
            param.put("userId", "");
        }
        param.put("isAll", true);
        param.put("topicType", 0);
        param.put("topicId", "");
        NetUtils.getNetAdapter().getTopiciscloseList(getOwnerName(), param, new AbsListNetCallback<FRebellion>(FRebellion.class) {
            @Override
            public void onSuc(List<FRebellion> fRebellions) {
                if (fRebellions == null || fRebellions.size() == 0) {
//                    onError(null, null);
                    initDataHudong(null);
                    return;
                }

                if(fRebellions.size()>=3){
                    fRebellions = fRebellions.subList(0,3);
                }

                initDataHudong(fRebellions);
            }

            @Override
            public void onError(Throwable ex, String errorMsg) {
                toast(R.string.loading_no_data);
            }

            @Override
            public void onEnd() {
                onNetFinish();
            }
        });

    }


    private ShareAdapter mAdapterHudong;



    private void initDataHudong(List<FRebellion> fRebellions) {
        if (fRebellions == null || fRebellions.size() == 0) {
            fRebellions = new ArrayList<>();
        }
        dataList.clear();
        dataList.addAll(fRebellions);
        if (mAdapterHudong == null) {
            mAdapterHudong = new ShareAdapter(getActivity(), dataList,this).setItemInternalClick(itemClickHudong);
            mAdapterHudong.setReward(4);
            rebllion_list.setAdapter(mAdapterHudong);
        }

        mAdapterHudong.setData(dataList);

    }

    private void initData(List<NewsItem> newsItems, int template) {
        if (mAdapter == null) {
            mAdapter = new MingshengFrgAdapter(getActivity(), null, template).setItemInternalClick(itemClick);
            mRecyclerView1.setAdapter(mAdapter);
        }
        mAdapter.setAct(isAct);
        mAdapter.setData(newsItems);

    }

    private List<NewsItem> newsItems;

    /**
     * 获取新闻列表点击量
     *
     * @param list
     */
    private void requestNewsClickCount(final List<NewsItem> list, final int templete) {
        if (ListUtils.isListValued(list)) {
            newsItems = new ArrayList<>();
            newsItems.addAll(list);
            List<NewsIdBean> newsIdList = new ArrayList<>();
            NewsIdBean newsBean;
            for (int i = 0; i < list.size(); i++) {
                String type = "10";//默认不返回点击量
                if (list.get(i) instanceof NewsItem) {
                    NewsItem item = (NewsItem) list.get(i);
                    newsBean = new NewsIdBean();
                    newsBean.setId(item.getUrlNewsId());
                    switch (item.getNewsType()) {
                        case Constances.NEWS_TYPE_GRAPHIC:
                        case Constances.NEWS_TYPE_AUDIO:
                        case Constances.NEWS_TYPE_VIDEO:
                            //新闻详情
                            type = "0";
                            break;
                        case Constances.NEWS_TYPE_LIVE:
                            //直播详情
                            type = "1";
                            break;
                        case Constances.NEWS_TYPE_H5:
                            //新闻详情
                            type = "0";
                            newsBean.setId(item.getNewsId());
                            break;
                        default:
                            //其他详情
                            newsBean.setId(item.getNewsId());
                            type = "10";
                            break;
                    }
                    newsBean.setType(type);
                    newsIdList.add(newsBean);
                } else {
                    newsBean = new NewsIdBean();
                    newsBean.setId("1");
                    newsBean.setType(type);
                    newsIdList.add(newsBean);
                }
            }
            if (ListUtils.isListValued(newsIdList)) {
                NewsListClickRequestBean requestBean = new NewsListClickRequestBean();
                requestBean.setNewsIds(newsIdList);
                Gson gson = new Gson();
                String newsId = gson.toJson(requestBean);
                RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), newsId);
                NetUtils.getNetAdapter().getViewsList(getOwnerName(), body, new AbsNetCallBack<NewsListClickVo>(NewsListClickVo.class) {
                    @Override
                    public void onSuc(NewsListClickVo newsListClickVo) {
                        if (null != newsListClickVo && ListUtils.isListValued(newsListClickVo.getResult())) {
                            List<NewsClickCountBean> countList = newsListClickVo.getResult();
                            for (int i = 0; i < countList.size(); i++) {
                                if (newsItems.get(i) instanceof NewsItem) {
                                    NewsItem item = (NewsItem) newsItems.get(i);
                                    if (item.getNewsType() == Constances.NEWS_TYPE_H5) {
                                        if (!TextUtils.isEmpty(item.getNewsId()) && countList.get(i).getId().equalsIgnoreCase(item.getNewsId())) {
                                            ((NewsItem) newsItems.get(i)).setReadCount(countList.get(i).getViews());
                                        }
                                    } else {
                                        if(item.getNewsType()== Constances.NEWS_TYPE_VIDEO){
                                            item.setViewType(GreatestAdapter.VIEWTYPE_VIDEO);
                                        }
                                        if (!TextUtils.isEmpty(item.getUrlNewsId()) && countList.get(i).getId().equalsIgnoreCase(item.getUrlNewsId())) {
                                            ((NewsItem) newsItems.get(i)).setReadCount(countList.get(i).getViews());
                                        }
                                    }
                                }
                            }
                        }
                        initData(newsItems, templete);

                    }

                    @Override
                    public void onEnd() {
                        super.onEnd();

                    }

                    @Override
                    public void onError(Throwable ex, String errorMsg) {
                        super.onError(ex, errorMsg);
                    }
                });
            }
        }
    }

    private synchronized void onNetFinish() {
        mIsLoading = false;
        mPullToRefreshView.onFooterRefreshComplete();
        mPullToRefreshView.onHeaderRefreshComplete();
    }

    OnItemInternalClick itemClick = new OnItemInternalClick() {
        @Override
        public void onItemInternalClick(View itemView, View view, int position) {
            ArrayList<Pair<String, String>> pairs = new ArrayList<>();
            pairs.add(new Pair<>("页面", "首页"));
            pairs.add(new Pair<>("栏目", tag));
            pairs.add(new Pair<>("行为类型", "点击"));
            GridsumWebDissector.getInstance().trackEvent(ShareMingshengFragment.this, "", ((NewsItem) mAdapter.getItem(position)).getNewsTitle(), "", 200, pairs);
            HashMap<String, String> map = new HashMap<>();
            for (Pair<String, String> p : pairs) {
                map.put(p.first, p.second);
            }
            SkipUtil.skipWithNewsItem(getActivity(), (NewsItem) mAdapter.getItem(position), map);
        }
    };


    OnItemInternalClick itemClickHudong = new OnItemInternalClick() {
        @Override
        public void onItemInternalClick(View itemView, View view, int position) {
            switch (view.getId()) {
                case R.id.item_rebllion_video_play:
                    itemPlayClick(itemView, view, position);
                    break;
                case R.id.li_doup:
                    if (!UserManager.isLoginS()) {
                        toLogin();
                        return;
                    }
                    if (mAdapterHudong.getItem(position) instanceof FRebellion) {
                        FRebellion fr = (FRebellion) mAdapterHudong.getItem(position);
                        doUp(fr, position);
                    }
//                    doUp(mAdapter.getItem(position), position);
                    break;
                case R.id.tv_anchor_comment:
                    if (!UserManager.isLoginS()) {
                        toLogin();
                        return;
                    }
                    if (mAdapterHudong.getItem(position) instanceof FRebellion) {
                        FRebellion fr = (FRebellion) mAdapterHudong.getItem(position);
                        Intent intent = new Intent(getActivity(), ShareDetailActivity.class);
                        intent.putExtra(EX_DATA, fr);
                        intent.putExtra(EX_COMMENT_TYPE, 4);
                        intent.putExtra(DO_UP_POS, position);
                        startActivity(intent);
                    }
//                    Intent intent = new Intent(getActivity(), ShareDetailActivity.class);
//                    intent.putExtra(EX_DATA, mAdapter.getItem(position));
//                    intent.putExtra(EX_COMMENT_TYPE, 4);
//                    intent.putExtra(DO_UP_POS, position);
//                    startActivity(intent);
                    break;
//                case R.id.tv_report:
//
//                    if (!UserManager.isLoginS()) {
//                        toLogin();
//                        return;
//                    }
//                    showConfirm(position);
//                    break;

            }
        }
    };


    private void itemPlayClick(View itemView, View view, int position) {
        if (mAdapterHudong.getItem(position) instanceof FRebellion) {
            FRebellion fRebellion = (FRebellion) mAdapterHudong.getItem(position);
            if (fRebellion != null) {
                SkipUtil.skipToVideoPlayWithCover(this, UrlUtils.linkUrls(Constances.ST_BASE_URL, fRebellion.getDiscloseVideo())
                        , fRebellion.getPlayedPos(), position, fRebellion.getCoverImage());
            }
        }

    }
    protected void toLogin() {
        Intent intent = new Intent(getContext(), LoginActivity.class);
        startActivityForResult(intent, CODE_REQUEST_LOGIN);
    }

    private ShareHolder lastHolder = null;
    Drawable showIcon = null;

    private void doUp(final FRebellion aDynamicsItem, final int position) {
        ParamsEditor pe = new ParamsEditor();
        pe.put("dynamicId", aDynamicsItem.getInfoId());
        pe.put("userId", UserManager.getInstance().getUser().getUserId());
        pe.put("fType", 2);

        RecyclerView.LayoutManager manager = rebllion_list.getLayoutManager();
        View lastView = manager.findViewByPosition(position);

        if (null != lastView) {
            lastHolder = (ShareHolder) rebllion_list.getChildViewHolder(lastView);
            if (null != lastHolder) {
                lastHolder.tv_anchor_up.setDrawableEnlarge();
            }
        }


        NetUtils.getNetAdapter().doUpForDynamics(getOwnerName(), pe.getEncryptedParams(UserManager.getInstance().getToken()), new AbsNetCallBack<SingleResult>(SingleResult.class) {
            @Override
            public void onSuc(SingleResult singleResult) {
                if (singleResult.isSuccess()) {

                    RecyclerView.LayoutManager manager = rebllion_list.getLayoutManager();
                    View lastView = manager.findViewByPosition(position);

                    ShareHolder lastHolder = null;
                    if (mAdapterHudong.getItem(position) instanceof FRebellion) {
                        FRebellion fr = (FRebellion) mAdapterHudong.getItem(position);

                        if (null != lastView) {
                            lastHolder = (ShareHolder) rebllion_list.getChildViewHolder(lastView);
                            if (fr.getIsDigg()) {
                                fr.setIsDigg(false);
                                fr.setCountDigg(fr.getCountDigg() - 1);

                                Drawable drawable = getResources().getDrawable(R.mipmap.icon_compere_btn_normal);
                                drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
                                lastHolder.tv_anchor_up.setDrawables(drawable, null, null, null);
                                lastHolder.tv_anchor_up.setTextColor(getResources().getColor(R.color.colorOpinionSelectNo));
                                showIcon = drawable;


                                if (UserManager.isLoginS()) {
                                    StatisticsMainInit.thumbsUpLog(UserManager.getInstance().getUser().getPhoneNumber(),fr.getInfoId(),
                                            fr.getDiscloseTitle(),2);
                                }else{
                                    StatisticsMainInit.thumbsUpLog("", fr.getInfoId(),
                                            fr.getDiscloseTitle(),2);
                                }

                            } else {
                                fr.setIsDigg(true);
                                fr.setCountDigg(fr.getCountDigg() + 1);

                                Drawable drawable = getResources().getDrawable(R.mipmap.icon_compere_btn_press);
                                drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
                                lastHolder.tv_anchor_up.setDrawables(drawable, null, null, null);
                                lastHolder.tv_anchor_up.setTextColor(getResources().getColor(R.color.colorTxRedMain_));
                                showIcon = drawable;
                                addInvitation(Constances.ADD_INTEGRAL_DOUP);

                                if (UserManager.isLoginS()) {
                                    StatisticsMainInit.thumbsUpLog(UserManager.getInstance().getUser().getPhoneNumber(),fr.getInfoId(),
                                            fr.getDiscloseTitle(),1);
                                }else{
                                    StatisticsMainInit.thumbsUpLog("", fr.getInfoId(),
                                            fr.getDiscloseTitle(),1);
                                }


                            }
                        }
                        int upCount = fr.getCountDigg();
                        if (upCount > 0) {
                            lastHolder.tv_anchor_up.setText(String.valueOf(upCount));
                        } else {
                            lastHolder.tv_anchor_up.setText("点赞");
                        }

                        //        mAdapter.notifyItemChanged(position);

                    }
                }
            }
        });
    }






    @Override
    public void onFooterRefresh(PullToRefreshView view) {
        mPullToRefreshView.postDelayed(new Runnable() {

            @Override
            public void run() {
                mPullToRefreshView.onFooterRefreshComplete();
            }
        }, 1);
    }




    @Override
    public void onHeaderRefresh(PullToRefreshView view) {
        mPullToRefreshView.postDelayed(new Runnable() {

            @Override
            public void run() {
                mPullToRefreshView.onHeaderRefreshComplete();
                getData();
            }
        }, 1000);

    }


    @Override
    public void OnTopicSelected(Integer selectInteger, TopicContent tp) {

    }
}
